<template>
  <s-layout class="set-wrap" title="视频列表" navbar="normal" tabbar="/pages/yy/live">
    <view class="flex flex-col gap-4 py-4 h-full" style="height: calc(100vh - 50px - 44px)">
      <view class="gap-4 items-center z-[999] grid grid-cols-3 px-4">
        <view
          class="flex gap-2 items-center bg-[#152B54] rounded-full overflow-hidden py-2 px-3 col-span-1"
          @click.stop="handlePublishClick()"
          v-if="state.config.is_video"
        >
          <image src="/static/20250901230740.png" class="size-6" mode="scaleToFill" />
          <view class="text-[14px] text-[#FDF27C] whitespace-nowrap"> 发布视频 </view>
        </view>
        <view class="flex gap-2 items-center bg-[#152B54] rounded-full overflow-hidden py-2 px-3 col-span-1" @click.stop="handleLiveClick(item)">
          <image src="/static/20250901230810.png" class="size-6" mode="scaleToFill" />
          <view class="text-[14px] text-[#FDF27C] whitespace-nowrap"> 直播列表 </view>
        </view>
        <view
          class="flex gap-2 items-center bg-[#152B54] rounded-full overflow-hidden py-2 px-3 col-span-1"
          @click.stop="handleStartLiveClick(item)"
          v-if="state.config.is_live"
        >
          <image src="/static/20250901230810.png" class="size-6" mode="scaleToFill" />
          <view class="text-[14px] text-[#FDF27C] whitespace-nowrap"> 开启直播</view>
        </view>
      </view>
      <!-- <view class="flex absolute right-3 bottom-[100px] flex-col gap-7 z-[999]">
        <view class="flex flex-col gap-3 justify-center items-center" id="live_user">
          <image :src="item.user.avatar" mode="scaleToFill" class="size-7 overflow-hidden rounded-full" />
          <view class="text-[10px] text-[#FFFFFF]">{{ item.user.nickname }}</view>
        </view>
      </view> -->
      <!-- 上下轮播图的视频 -->
      <!-- /@click="handleVideoClick" -->
      <s-zhibo v-if="state.list.length > 0" :videoList="state.list" @change="videoChange" @loadMore="loadMoreVideo" style="height: 75vh"> </s-zhibo>
      <view v-else class="loading-container">
        <text>加载中...</text>
      </view>
    </view>

    <!-- 评论弹框 -->
  </s-layout>
</template>

<script setup>
  import { ref, onMounted } from 'vue';
  import sheep from '@/sheep';

  const state = ref({
    list: [],
    loading: true,
    page: 1,
    limit: 10,
    config: {
      is_live: false,
      is_video: false,
    },
  });

  const commentPopupVisible = ref(false);
  const commentContent = ref('');
  const currentVideo = ref(null);

  onMounted(() => {
    videoList();
  });
  livePower();

  function livePower() {
    sheep.$api.yy
      .livePower()
      .then((res) => {
        if (res.code === 1) {
          state.value.config = res.data;
        }
      })
      .catch((err) => {
        console.error('直播权限失败:', err);
      });
  }

  // 获取视频列表
  function videoList() {
    let params = {
      page: state.value.page,
      limit: state.value.limit,
    };

    sheep.$api.yy
      .videoList(params)
      .then((res) => {
        if (res.code === 1 && res.data) {
          // 将API返回的视频数据转换为s-zhibo组件�要的格式
          // const formattedVideos = res.data.data.map((item) => ({
          //   src: item.file || item.url, // 视频链接
          //   poster: item.cover || item.poster, // 封面�
          //   title: item.title, // 视频标题
          //   // 可以添加其他�要的数据
          // }));
          console.log('res==> ', res);
          state.value.list = res.data.data;
          state.value.loading = false;
        }
      })
      .catch((err) => {
        console.error('获取视频列表失败:', err);
        state.value.loading = false;
      });
  }

  // 视频切换事件
  function videoChange(e) {
    console.log('视频切换:', e);
    // 可以在这里处理视频切换�辑
  }

  // 加载更多视频
  function loadMoreVideo() {
    if (state.value.loading) return; // 防止重复请求

    state.value.loading = true;
    state.value.page++;

    let params = {
      page: state.value.page,
      limit: state.value.limit,
    };

    sheep.$api.yy
      .videoList(params)
      .then((res) => {
        if (res.code === 1 && res.data && res.data.data && res.data.data.length > 0) {
          // 使用Set去重，避免重复数据
          const existingIds = new Set(state.value.list.map((item) => item.id));

          // 过滤新数据，只添加不存在的视频
          const newVideos = res.data.data.filter((item) => !existingIds.has(item.id));

          if (newVideos.length > 0) {
            // 将新加载的视频添加到列表中，保持原始数据结构
            state.value.list = [...state.value.list, ...newVideos];
            console.log('加载更多视频成功，新增:', newVideos.length, '个视频');
          } else {
            console.log('没有新的视频数据');
          }
        } else {
          console.log('没有更多视频数据');
        }
        state.value.loading = false;
      })
      .catch((err) => {
        console.error('加载更多视频失败:', err);
        state.value.page--; // 请求失败时回退页码
        state.value.loading = false;
      });
  }

  // 视频点击事件
  function handleVideoClick(e) {
    console.log('视频点击:', e);
    // 可以在这里处理视频点击�辑
  }

  // 评论点击事件
  function handleCommentClick(item) {
    console.log('item==> ', item);
    currentVideo.value = item;
    commentPopupVisible.value = true;
  }

  // 关闭评论弹框
  function closeCommentPopup() {
    commentPopupVisible.value = false;
    commentContent.value = '';
  }
  // uni.navigateTo({
  //   url: `/pages/yy/liveStreaming`,
  // });

  // 提交评论
  function submitComment() {
    if (!commentContent.value.trim()) {
      uni.showToast({
        title: '请输入评论内容',
        icon: 'none',
      });
      return;
    }

    console.log('提交评论:', {
      videoId: currentVideo.value?.id,
      content: commentContent.value,
    });

    // 这里可以添加评论提交的API调用
    // sheep.$api.yy.submitComment({
    //   video_id: currentVideo.value?.id,
    //   content: commentContent.value
    // }).then(res => {
    //   if (res.code === 1) {
    //     uni.showToast({
    //       title: '评论成功',
    //       icon: 'success'
    //     });
    //     closeCommentPopup();
    //   }
    // });

    // 临时模拟评论成功
    uni.showToast({
      title: '评论成功',
      icon: 'success',
    });
    closeCommentPopup();
  }

  function handlePublishClick(item) {
    // 跳转到发布视频页面，并携带视频id
    uni.navigateTo({
      url: `/pages/yy/publishVideo`,
    });
  }

  function handleLiveClick(item) {
    uni.navigateTo({
      url: `/pages/yy/videoList`,
    });
  }
  // uni.navigateTo({
  //   url: `/pages/yy/videoList`,
  // });
  function handleStartLiveClick(item) {
    // 获取平台
    // let platform = uni.getSystemInfoSync().platform;
    // console.log('🚀 ~ handleStartLiveClick ~ platform:', platform);
    uni.navigateTo({
      url: `/pages/yy/liveStreaming`,
    });
  }

  //  uni.navigateTo({
  // url: `/pages/yy/liveStreaming`,
  //  });
</script>

<style lang="scss" scoped>
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }

  .video-info {
    position: absolute;
    bottom: 30px;
    left: 20px;
    z-index: 10;
    color: #fff;

    .video-title {
      font-size: 16px;
      text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
    }
  }

  // 评论弹框样式
  .comment-popup {
    background-color: #fff;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    padding: 20px;

    &-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    &-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    &-close {
      padding: 5px;
    }

    &-content {
      display: flex;
      flex-direction: column;
      gap: 15px;
    }
  }

  .comment-input-container {
    width: 100%;
  }

  .comment-submit-btn {
    background-color: #0788c8;
    border-radius: 8px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;

    .comment-submit-text {
      color: #fff;
      font-size: 14px;
    }
  }
</style>
